import React, { Component } from 'react'

import {connect} from 'react-redux';

import {getDetail,addLove} from '../../store/actions/detail';

import {bindActionCreators} from 'redux';

import {RouteComponentProps} from 'react-router-dom';

import {ListProp} from '../../types/list.d';

import moment from 'moment';

// 里面的字符可以根据自己的需要进行调整
moment.locale('zh-cn', {
    relativeTime: {
        future: '%s内',
        past: '%s前',
        s: '几秒',
        ss: '%d秒',
        m: '1分钟',
        mm: '%d分钟',
        h: '1小时',
        hh: '%d小时',
        d: '1天',
        dd: '%d天',
        M: '1个月',
        MM: '%d个月',
        y: '1年',
        yy: '%d年'
    }
})

interface Iprops extends RouteComponentProps{
    getDetail:(id:number) => void,
    match:any,
    detail:ListProp,
    addLove:(target:ListProp) => void,
    loveList:ListProp[]
}


//1.取id  //2. id获取指定的对象
class Detail extends Component <Iprops>{

    componentDidMount(){
        let id = this.props.match.params.id;
        this.props.detail.id === -1 && this.props.getDetail(id);
    }
    render() {
        let {pic,desc,name,num,id,comment} = this.props.detail;
        let loveIndex = this.props.loveList.findIndex(item => item.id === id)
        return (
            <div>
                <div>
                    <div>
                        <img src={pic} alt=""/>
                        <p>{name}</p>
                        <span>收藏：{num}</span>
                        <p>{desc}</p>
                    </div>
                    <div>
                        最新评论：
                        {comment.map(item => <div key={item.id}>
                            <span>lixd</span>
                            <span>{moment(item.time).fromNow()}</span>
                            <span>{item.con}</span>
                        </div>)}
                    </div>
                </div>
                <footer>
                    <span onClick={this.goComment}>评论</span>
                    <span onClick={this.addLoveFood}  className={loveIndex !== -1 ? 'active' : ''}>收藏</span>
                </footer>
            </div>
        )
    }

    //收藏
    addLoveFood = () => {
        this.props.addLove(this.props.detail)
    }

    //去评论界面
    goComment = () => {
        this.props.history.push(`/comment/${this.props.detail.id}`)
    }

    
}


let stateMapToProps = (state:any) => {
    return {
        detail:state.detail,
        loveList:state.loveList
    }
}

let dispatchMapToProps = (dispatch:any) => {
    return bindActionCreators({getDetail,addLove},dispatch)
}

export default connect(stateMapToProps,dispatchMapToProps)(Detail)
